package com.js.lib.annotation.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.google.common.util.concurrent.RateLimiter;
import com.js.lib.annotation.RateLimit;
import com.js.lib.exception.CustomException;

/**
 * 限流拦截器，并发数限制
 * @author kenny
 * @since 2019-09-19 11:59
 */
@Component
@Scope
@Aspect
public class RateLimitAop {

    @Pointcut("@annotation(com.js.lib.annotation.RateLimit)")
    public void serviceLimit() {
    }

    @Around("serviceLimit() && @annotation(rateLimit)")
    public Object around(ProceedingJoinPoint joinPoint,RateLimit rateLimit) throws Throwable {

        Object obj;
        if (RateLimiter.create(rateLimit.limiterNumber()).tryAcquire()) {
            obj = joinPoint.proceed();
        } else {
            // 请求繁忙
            throw new CustomException(102008,"请求繁忙",null);
        }
        return obj;
    }
}
